package com.ruoyi.background.service.impl;

import com.ruoyi.background.domain.AppGradeRecord;
import com.ruoyi.background.domain.AppLotteryPrize;
import com.ruoyi.background.domain.AppLotteryRecord;
import com.ruoyi.background.domain.AppWechatUser;
import com.ruoyi.background.mapper.AppGradeRecordMapper;
import com.ruoyi.background.mapper.AppLotteryPrizeMapper;
import com.ruoyi.background.mapper.AppLotteryRecordMapper;
import com.ruoyi.background.service.IAppLotteryPrizeService;
import com.ruoyi.background.service.IAppSiteService;
import com.ruoyi.background.service.IAppWechatUserService;
import com.ruoyi.background.utils.CONFIG_KEY;
import com.ruoyi.background.utils.REDIS_KEY;
import com.ruoyi.background.utils.SYS_CONSTANT;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 积分抽奖奖品Service业务层处理
 *
 * @author susu
 * &#064;date  2024-08-24
 */
@Service
public class AppLotteryPrizeServiceImpl implements IAppLotteryPrizeService {

    private static final Logger log = LoggerFactory.getLogger(AppLotteryPrizeServiceImpl.class);
    @Autowired
    private AppLotteryPrizeMapper appLotteryPrizeMapper;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IAppWechatUserService wechatUserService;

    @Autowired
    private AppGradeRecordMapper appGradeRecordMapper;


    @Autowired
    private AppLotteryRecordMapper appLotteryRecordMapper;

    @Autowired
    private IAppSiteService siteService;

    @Autowired
    private RedisCache redisCache;

    // 1.获取事务管理器，指定数据源
    @Autowired
    private PlatformTransactionManager transactionManager;
    // 2.定义事务属性（隔离级别、传播特性、超时时间、是否只读等）
    @Autowired
    private TransactionDefinition transactionDefinition;

    /**
     * 生成预抽奖结果
     *
     * @return 结果
     */
    @Override
    public int createUserPreLottery() {
        List<AppWechatUser> userList = wechatUserService.selectAppWechatUserList(new AppWechatUser());
        int num = 0; //必中的人
        int num2 = 0;
        int i1 = 0;
        int i2 = 0;
        int i3 = 0;
        //不中的奖品
        AppLotteryPrize notWinPrize = SYS_CONSTANT.NOT_WIN_PRIZE;
        //必中的奖品
        AppLotteryPrize mustWinPrize = SYS_CONSTANT.MUST_WIN_PRIZE;
        for (AppWechatUser wechatUser : userList) {
            if (ObjectUtils.isEmpty(wechatUser) || wechatUser.getUserId() == null)
                continue;
            // 每个人预抽奖的结果列表
            String perKey = REDIS_KEY.APP_LOTTERY_PRIZE_USER_PER + wechatUser.getUserId();
            List<AppUserPrePrize> prePrizeList = new ArrayList<>();
            //判断是否必中
            if (SYS_CONSTANT.WIN_USER_LIST.contains(wechatUser.getUserId())) {
                AppUserPrePrize prePrize = new AppUserPrePrize();
                prePrize.setPrize(mustWinPrize);
                prePrize.setUserId(wechatUser.getUserId());
                prePrize.setPrizeId(mustWinPrize.getId());
                prePrizeList.add(prePrize);
                num++;
            } else {//不是必中
                //生成随机数
                Random random = new Random();
                int randomNumber = random.nextInt(3);
                switch (randomNumber) {
                    case 0:
                        i1++;
                        break;
                    case 1:
                        i2++;
                        break;
                    case 2:
                        i3++;
                        break;
                }
                for (int i = 0; i < 3; i++) {
                    AppUserPrePrize prePrize = new AppUserPrePrize();
                    if (i == randomNumber) {
                        prePrize.setPrize(mustWinPrize);
                        prePrize.setUserId(wechatUser.getUserId());
                        prePrize.setPrizeId(mustWinPrize.getId());
                        num2++;
                        System.out.println(wechatUser.getPhoneNumber() + "第" + i + "次中奖");
                    } else {
                        prePrize.setPrize(notWinPrize);
                        prePrize.setUserId(wechatUser.getUserId());
                        prePrize.setPrizeId(notWinPrize.getId());
                    }
                    prePrizeList.add(prePrize);
                }

            }
            redisCache.deleteByKey(perKey);
            if (!ObjectUtils.isEmpty(prePrizeList)) {
                redisCache.setCacheList(perKey, prePrizeList);
                redisCache.expire(perKey, 60 * 24 * 7, TimeUnit.MINUTES);
            }
        }
        log.info("必中人数：" + num);
        log.info("不是必中人数：" + num2);
        log.info("第一次中奖人数：" + i1);
        log.info("第二次中奖人数：" + i2);
        log.info("第三次中奖人数：" + i3);
        return 0;
    }

    /**
     * 设置数量
     *
     * @return
     */
    @Override
    public int setNowWinNum() {
        String nowWinNumKey = REDIS_KEY.APP_LOTTERY_WINNING_NUM;
        int lotteryIndex = 5;
        Integer maxNum = 600 - 34;
        Integer a = appLotteryRecordMapper.countNumWithOutMustWin(lotteryIndex); // 排除必中的
        if (a == null) a = 0;
        redisCache.setCacheObject(nowWinNumKey, a);
        int i = maxNum - a;
        log.info("排除必中的中奖：" + a);
        log.info("排除必中奖品剩余：" + i);
        //当前中奖的
//        int m = 34; //必中的数量
//        int n = 11; //必中有账号
//        int lotteryIndex = 4;
//        Integer a = appLotteryRecordMapper.countNumWithOutMustWin(lotteryIndex); // 排除必中的
//        Integer b = appLotteryRecordMapper.countNumWithMustWim(lotteryIndex); // 必中的已经中奖
//        Integer c = m - n; //必中没有账号
//        int d = n - b; //必中有账号 但是没有抽奖
//        int e = 1970 - a; // 排除必中的奖品剩余数量  剩余数量
//        int f = b + d + c; //必中
//        int t = a + e + f;
//        System.out.println("第" + lotteryIndex + "轮抽奖统计数量");
//        System.out.println("必中人数：" + m);
//        System.out.println("必中无账号人数：" + c);
//        System.out.println("必中的有账号已抽奖人数：" + b);
//        System.out.println("必中的有账号但是没有抽奖" + d);
//        System.out.println("----------");
//        System.out.println("排除必中人数已经中奖人数:" + a);
//        System.out.println("--------------------");
//        System.out.println("排除必中的奖品剩余数量" + e);
//        System.out.println("奖品总数量：" + t);
//        redisCache.setCacheObject(nowWinNumKey, a);
        return 0;
    }

    /**
     * 统计用户是否最后一个关卡
     *
     * @return
     */
    @Override
    public int initUserIsFinale() {
        int a = 0;
        int b = 0;
        int c = 0;
        List<AppWechatUser> userList = wechatUserService.selectAppWechatUserList(new AppWechatUser());
        for (AppWechatUser appWechatUser : userList) {
            Long userId = appWechatUser.getUserId();
            if(SYS_CONSTANT.WIN_USER_LIST.contains(userId)){
                log.info(appWechatUser.getPhoneNumber()+"必中");
                c++;
                String key = REDIS_KEY.APP_USER_FINAL_FLAG_KEY + userId;
                redisCache.setCacheObject(key, 1);
            }else {
//                boolean flag = siteService.userIsFinalSite(userId);
//                if (flag) {
//                    a++;
//                    log.info(appWechatUser.getPhoneNumber() + " 到达最后一个关卡");
//                } else {
//                    b++;
//                    log.info(appWechatUser.getPhoneNumber() + " 未到达最后一个关卡！");
//                }
            }
        }
        log.info("到达最后一个关卡的人：" + a);
        log.info("未到达最后一个关卡：" + b);
        log.info("必中：" + c);
        log.info("总人数：" + (a + b));
        log.info("list长度：" + userList.size());
        return 0;
    }

    /**
     * 查询积分抽奖奖品
     *
     * @param id 积分抽奖奖品主键
     * @return 积分抽奖奖品
     */
    @Override
    public AppLotteryPrize selectAppLotteryPrizeById(Long id) {
        String key = REDIS_KEY.APP_LOTTERY_PRIZE_ONE_KEY + id;
        AppLotteryPrize appLotteryPrize = redisCache.getCacheObject(key);
        if (ObjectUtils.isEmpty(appLotteryPrize)) {
            appLotteryPrize = appLotteryPrizeMapper.selectAppLotteryPrizeById(id);
            redisCache.setCacheObject(key, appLotteryPrize);
        }
        return appLotteryPrize;
    }

    /**
     * 取数量不为 0 的奖品
     *
     * @return list
     */
    public List<AppLotteryPrize> getPrizeNumNot0() {
        String key = REDIS_KEY.APP_LOTTERY_PRIZE_NOT_ZERO_LIST;
        List<AppLotteryPrize> prizeList = redisCache.getCacheList(key);
        if (ObjectUtils.isEmpty(prizeList)) {
            log.info("抽奖数据库查询数据");
            prizeList = appLotteryPrizeMapper.getPrizeNumNot0();
            // 数据库查询的数据 生成每个奖品的 开始 结束 区间
            double cumulativeProbability = 0;
            for (int i = 0; i < prizeList.size(); i++) { // 每个奖品去生成的区间
                prizeList.get(i).setBeginProbability(cumulativeProbability); // 开始值
                cumulativeProbability += prizeList.get(i).getRange();
                prizeList.get(i).setCumulativeProbability(cumulativeProbability); // 结束值
            }
            redisCache.deleteByKey(key);
            redisCache.setCacheList(key, prizeList);
            redisCache.expire(key, 30, TimeUnit.MINUTES);
        }
        return prizeList;
    }


    /**
     * 查询积分抽奖奖品列表
     *
     * @param appLotteryPrize 积分抽奖奖品
     * @return 积分抽奖奖品
     */
    @Override
    public List<AppLotteryPrize> selectAppLotteryPrizeList(AppLotteryPrize appLotteryPrize) {
        return appLotteryPrizeMapper.selectAppLotteryPrizeList(appLotteryPrize);
    }

    /**
     * 新增积分抽奖奖品
     *
     * @param appLotteryPrize 积分抽奖奖品
     * @return 结果
     */
    @Override
    public int insertAppLotteryPrize(AppLotteryPrize appLotteryPrize) {
        //数量变动  清楚缓存的数据
        redisCache.deleteObject("sys.app.cacheList.numnotzore.prize");
        appLotteryPrize.setCreateTime(DateUtils.getNowDate());
        appLotteryPrize.setCreateBy(SecurityUtils.getUsername());
        appLotteryPrize.setUpdateTime(DateUtils.getNowDate());
        appLotteryPrize.setUpdateBy(SecurityUtils.getUsername());
        return appLotteryPrizeMapper.insertAppLotteryPrize(appLotteryPrize);
    }

    /**
     * 修改积分抽奖奖品
     *
     * @param appLotteryPrize 积分抽奖奖品
     * @return 结果
     */
    @Override
    public int updateAppLotteryPrize(AppLotteryPrize appLotteryPrize) {
        AppLotteryPrize prize = this.selectAppLotteryPrizeById(appLotteryPrize.getId());
        if (ObjectUtils.isEmpty(prize)) throw new RuntimeException("对象不存在");
        if (0 != prize.getDelFlag()) throw new RuntimeException("对象已删除！");
        appLotteryPrize.setUpdateTime(DateUtils.getNowDate());
        appLotteryPrize.setUpdateBy(SecurityUtils.getUsername());
        //数量变动  清楚缓存的数据
        redisCache.deleteObject("sys.app.cacheList.numnotzore.prize");
        return appLotteryPrizeMapper.updateAppLotteryPrize(appLotteryPrize);
    }

    /**
     * 修改状态
     *
     * @param id     id
     * @param status 状态
     * @return 结果
     */
    @Override
    public int changeStatus(Long id, Integer status) {
        AppLotteryPrize prize = this.selectAppLotteryPrizeById(id);
        if (ObjectUtils.isEmpty(prize)) throw new RuntimeException("对象不存在");
        if (0 != prize.getDelFlag()) throw new RuntimeException("对象已删除！");
        AppLotteryPrize appLotteryPrize = new AppLotteryPrize();
        appLotteryPrize.setId(id);
        appLotteryPrize.setStatus(status);
        appLotteryPrize.setUpdateTime(DateUtils.getNowDate());
        appLotteryPrize.setUpdateBy(SecurityUtils.getUsername());
        //数量变动  清楚缓存的数据
        redisCache.deleteObject("sys.app.cacheList.numnotzore.prize");
        return appLotteryPrizeMapper.updateAppLotteryPrize(appLotteryPrize);
    }

    /**
     * 批量删除积分抽奖奖品
     *
     * @param ids 需要删除的积分抽奖奖品主键
     * @return 结果
     */
    @Override
    public int deleteAppLotteryPrizeByIds(Long[] ids) {
        return appLotteryPrizeMapper.deleteAppLotteryPrizeByIds(ids);
    }

    /**
     * 删除积分抽奖奖品信息
     *
     * @param id 积分抽奖奖品主键
     * @return 结果
     */
    @Override
    public int deleteAppLotteryPrizeById(Long id) {
        return appLotteryPrizeMapper.deleteAppLotteryPrizeById(id);
    }

    /**
     * 用户积分抽奖
     *
     * @return 中奖奖品
     */
    @Override
    public AppLotteryPrize lotteryPrize() {
//        boolean b = userIsFinalSite(SecurityUtils.getUserId());
//        if (!b) {
//            throw new ServiceException("您未解锁最后一个关卡，无抽奖资格！");
//        }
        //抽奖需要的积分
        int needGrade = 300;
        //取用户积分
        AppWechatUser wechatUser = wechatUserService.selectAppWechatByUserId();
        int userGrade = wechatUser.getGrade();
        //判断用户是否积分够抽奖
        if (userGrade < needGrade) throw new RuntimeException("您的积分不足" + needGrade + ",无法抽奖！");
        int lotteryIndex = 5;
        // 中奖的奖品
        AppLotteryPrize userPrize;
        //判断第几轮抽奖
        userPrize = this.userPrize2(wechatUser, needGrade, lotteryIndex);
        //抽奖奖品为空 抛出异常
        if (ObjectUtils.isEmpty(userPrize) || userPrize.getId() == null)
            throw new RuntimeException("活动过于火爆，请稍后再试！");
        return userPrize;
    }

    /**
     * 第二轮抽奖
     *
     * @param wechatUser   抽奖的用户
     * @param needGrade    需要的积分
     * @param lotteryIndex 当前处于第几轮抽奖
     * @return 中奖结果
     */
    public AppLotteryPrize userPrize2(AppWechatUser wechatUser, int needGrade, int lotteryIndex) {
        // 用户抽奖的奖品
        AppLotteryPrize userPrize = new AppLotteryPrize();
        //判断是否达到限定数量
        String nowWinNumKey = REDIS_KEY.APP_LOTTERY_WINNING_NUM;
        Integer nowWinNum = redisCache.getCacheObject(nowWinNumKey); //当前中奖的数量
        if (ObjectUtils.isEmpty(nowWinNum)) { //中奖数量为空 重新查询数据库 如果数据库没有记录 设置为0
            Integer integer = appLotteryRecordMapper.countWinNumLotteryByIndex(lotteryIndex);
            nowWinNum = integer == null ? 0 : integer;
            redisCache.setCacheObject(nowWinNumKey, nowWinNum);
        }
        // 是否在必中的名单内 必中的名单 不受到数量的限制
        if (this.userIsMustWin()) {
            userPrize = this.getUserPrePrize();
        } else { // 不是必中的人
            if (this.isMaxWinSum(nowWinNum)) {  // 判断是否到了最大的中奖数量 达到看最大的中奖数量 那么就是不中奖
                userPrize = SYS_CONSTANT.NOT_WIN_PRIZE;
            } else { // 没有到最大的数量 取预生成的结果
                userPrize = this.getUserPrePrize();
            }
            // 如果中奖 那么所有的中奖数+1 写入缓存
            if ("中奖".equals(userPrize.getName())) {
                nowWinNum++;
                redisCache.setCacheObject(REDIS_KEY.APP_LOTTERY_WINNING_NUM, nowWinNum);
            }
        }
        // 扣减积分 插入记录  异步执行
        wechatUser.setUserName(SecurityUtils.getLoginUser().getUser().getNickName());
        wechatUser.setDeptId(SecurityUtils.getDeptId());
        wechatUser.setDeptName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
        this.setLotteryData(userPrize, wechatUser, needGrade, lotteryIndex);
        // 结束 返回用户奖品
        return userPrize;
    }

    /**
     * 去用户的 预想的结果
     *
     * @return 结果
     */
    public AppLotteryPrize getUserPrePrize() {
        String perKey = REDIS_KEY.APP_LOTTERY_PRIZE_USER_PER + SecurityUtils.getUserId();
        List<AppUserPrePrize> prePrizeList = redisCache.getCacheList(perKey);
        AppLotteryPrize appLotteryPrize = new AppLotteryPrize();
        if (!ObjectUtils.isEmpty(prePrizeList)) { // 预计抽奖的奖品不为空 取第一个奖品 同时去掉第一个奖品 重新设置缓存
            appLotteryPrize = prePrizeList.get(0).getPrize();
            List<AppUserPrePrize> newList = prePrizeList.stream().skip(1).collect(Collectors.toList());
            redisCache.deleteByKey(perKey);
            if (!ObjectUtils.isEmpty(newList)) {
                redisCache.setCacheList(perKey, newList);
                redisCache.expire(perKey, 60 * 24 * 7, TimeUnit.MINUTES);
            }
        } else { //没有预计的结果 也就是10次内必中了 本轮不在中奖
            appLotteryPrize = SYS_CONSTANT.NOT_WIN_PRIZE;
        }
        return appLotteryPrize;
    }

    /**
     * 用户抽奖
     *
     * @return 抽奖的奖品
     */
    public AppLotteryPrize userLottery() {
        AppLotteryPrize userPrize = new AppLotteryPrize();
        // 取奖品不为0的奖品
        List<AppLotteryPrize> prizeList = this.getPrizeNumNot0();
        // 随机数最大的区间
        double cumulativeProbability = prizeList.get(prizeList.size() - 1).getCumulativeProbability();
        Random random = new Random();
        double randomNumber = random.nextDouble() * cumulativeProbability;
        for (AppLotteryPrize prize : prizeList) {
            if (randomNumber <= prize.getCumulativeProbability() && randomNumber > prize.getBeginProbability()) {
                userPrize = prize;
            }
        }
        // 奖品为空  返回不中奖
        if (ObjectUtils.isEmpty(userPrize) || userPrize.getId() == null) {
            Long id = Long.valueOf(sysConfigService.selectConfigByKey(CONFIG_KEY.LOTTERY_NOT_WIM_ID));
            userPrize = this.selectAppLotteryPrizeById(id);
        }
        return userPrize;
    }


    /**
     * 判断用户是否必中
     *
     * @return true 是必中 false 不是必中
     */
    private boolean userIsMustWin() {
        return SYS_CONSTANT.WIN_USER_LIST.contains(SecurityUtils.getUserId());
    }


    /**
     * 判断用户是否到达最后一个关卡
     *
     * @return true 到达  false 未到达
     */
    private boolean userIsFinalSite(long userId) {
        String key = REDIS_KEY.APP_USER_FINAL_FLAG_KEY + userId;
        Integer cacheObject = redisCache.getCacheObject(key);
        if (ObjectUtils.isEmpty(cacheObject)) {
            return siteService.userIsFinalSite(userId);
        }
        return cacheObject == 1;
    }

    /**
     * 判断是否到了最大的中奖数量
     *
     * @return true 到了最大的中奖数量  false 未到
     */
    private boolean isMaxWinSum(int nowWinNum) {
        // 最大的中奖数量
        return nowWinNum >= 566;
    }

    /**
     * 第一轮抽奖的逻辑
     *
     * @return 用户中奖的奖品
     */
    @Transactional
    public AppLotteryPrize userPrize1(AppWechatUser wechatUser, int needGrade, int lotteryIndex) {
        // 查询是否中奖
        AppLotteryRecord query = new AppLotteryRecord();
        query.setUserId(SecurityUtils.getUserId());
        query.setLotteryIndex(1);
        List<AppLotteryRecord> records = appLotteryRecordMapper.selectAppLotteryRecordList(query);
        // 用户未抽奖 直接 中奖
        AppLotteryPrize userPrize = new AppLotteryPrize();
        if (ObjectUtils.isEmpty(records) || records.size() == 0) {
            log.info("抽奖人：" + wechatUser.getPhoneNumber() + "，第一次抽奖，必中");
            Long id = Long.valueOf(sysConfigService.selectConfigByKey("app.lottery.bizhong.id"));
            userPrize = this.selectAppLotteryPrizeById(id);
        } else {
            log.info("抽奖人：" + wechatUser.getPhoneNumber() + "，非第一次抽奖，谢谢参与");
            Long id = Long.valueOf(sysConfigService.selectConfigByKey("app.lottery.buzhong.id"));
            userPrize = this.selectAppLotteryPrizeById(id);
            //找现在有哪些奖品的
//            List<AppLotteryPrize> prizes = this.getPrizeNumNot0();
//            double cumulativeProbability = 0;
//            for (AppLotteryPrize prize : prizes) {
//                prize.setBeginProbability(cumulativeProbability);
//                cumulativeProbability += prize.getRange();
//                prize.setCumulativeProbability(cumulativeProbability);
//            }
//            Random random = new Random();
//            double randomNumber = random.nextDouble() * cumulativeProbability;
//            log.info("抽奖人：" + wechatUser.getPhoneNumber() + "，生成随机数：" + randomNumber);
//            for (AppLotteryPrize prize : prizes) {
//                log.info("奖品id:" + prize.getId() + ",开始区间" + prize.getBeginProbability() + "，结束区间" + prize.getCumulativeProbability());
//                if (randomNumber <= prize.getCumulativeProbability() && randomNumber > prize.getBeginProbability()) {
//                    log.info("落在区间，中奖！奖品id：" + prize.getId() + ",中奖手机号：" + wechatUser.getPhoneNumber());
//                    userPrize = prize;
//                } else {
//                    log.info("未落在区间");
//                }
//            }
        }
        if (ObjectUtils.isEmpty(userPrize)) throw new RuntimeException("当前参与人数过多，请稍后再试！");
        wechatUser.setUserName(SecurityUtils.getLoginUser().getUser().getNickName());
        wechatUser.setDeptId(SecurityUtils.getDeptId());
        wechatUser.setDeptName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
        this.setLotteryData(userPrize, wechatUser, needGrade, lotteryIndex);
        return userPrize;
    }


    /**
     * 处理抽奖之后的数据
     *
     * @param appLotteryPrize 中奖的奖品
     * @param wechatUser      用户
     * @param grade           消耗的分数
     */
    @Async
    public void setLotteryData(AppLotteryPrize appLotteryPrize, AppWechatUser wechatUser, int grade, int lotteryIndex) {
        // 这里使用编程式事务（不使用声明式事务）确保数据一致性
        // 开启事务 返回状态
        TransactionStatus transactionStatus = null;
        try {
            //处理数据
            //插入积分使用记录数据
            AppGradeRecord appGradeRecord = new AppGradeRecord();
            appGradeRecord.setUserId(wechatUser.getUserId());
            appGradeRecord.setType(1);
            appGradeRecord.setGrade(grade);
            appGradeRecord.setBeforeGrade(wechatUser.getGrade());
            appGradeRecord.setRemark("系统积分抽奖");
            appGradeRecord.setCreateTime(DateUtils.getNowDate());
            //用户积分
            AppWechatUser updateUser = new AppWechatUser();
            updateUser.setId(wechatUser.getId());
            updateUser.setGrade(wechatUser.getGrade() - grade);
            // 抽奖记录
            AppLotteryRecord record = new AppLotteryRecord();
            // 第几轮抽奖
            record.setLotteryIndex(lotteryIndex);
            record.setUserId(wechatUser.getUserId());
            record.setPrizeId(appLotteryPrize.getId());
            record.setCreateBy("sysLottery");
            record.setUserName(wechatUser.getUserName());
            record.setDeptId(wechatUser.getDeptId());
            record.setPrizeName(appLotteryPrize.getName());
            record.setPrizeNum(1);
            record.setCreateTime(DateUtils.getNowDate());
            record.setPrizeImage(appLotteryPrize.getImage());
            record.setPrizeCode("ZT2410111400");
            //修改奖品的数据 缓存已经设置最大的数量  这里不在设置了
//             AppLotteryPrize updatePrize = new AppLotteryPrize();
//             updatePrize.setId(appLotteryPrize.getId());
//             updatePrize.setNum(appLotteryPrize.getNum() - 1);
//             updatePrize.setUpdateTime(DateUtils.getNowDate());
//             updatePrize.setCreateBy("SystemLotteryChange");
            transactionStatus = transactionManager.getTransaction(transactionDefinition);
            //插入积分消耗的记录
            appGradeRecordMapper.insertAppGradeRecord(appGradeRecord);
            //修改用户的积分
            wechatUserService.updateAppWechatUser(updateUser);
            //插入积分抽奖记录
            appLotteryRecordMapper.insertAppLotteryRecord(record);
            // 修改奖品数量
            // appLotteryPrizeMapper.updateAppLotteryPrize(updatePrize);
            // 提交事务
            transactionManager.commit(transactionStatus);
        } catch (Exception e) {
            System.out.println(e);
            // 抽奖回滚事务
            if (transactionStatus != null) {
                String id = appLotteryPrize.getId() == null ? "无id" : String.valueOf(appLotteryPrize.getId());
                log.info("抽奖事务回滚!手机号:" + wechatUser.getPhoneNumber() + ",奖品:" + id);
                transactionManager.rollback(transactionStatus);
            }
        }
    }


}
